package com.gem.day15.exercise;

/**
 * 定义两条线程,一条线程负责输出数字,另一条线程负责输出字母,
 * 要求两条线程同时启动,打印出如下效果:
 * 12A34B56C78D...5152Z
 * 
 * 线程通信方式实现
 */
public class Exercise2 {
	public static void main(String[] args) {
		Object object = new Object();
		Thread t1 = new PrintLetter(object);
		Thread t2 = new PrintNumber(object);
		t1.setPriority(Thread.MIN_PRIORITY);
		t2.setPriority(Thread.MAX_PRIORITY);
		t2.start();
		try {
			Thread.sleep(1);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		t1.start();
	}
}

class PrintLetter extends Thread {
	private Object lock;

	public PrintLetter(Object lock) {
		this.lock = lock;
	}

	@Override
	public void run() {
		synchronized (lock) {
			for (char c = 'A'; c <= 'Z'; c++) {
				System.out.print(c);
				try {
					//唤醒
					lock.notifyAll();
					//等待
					if (c != 'Z') {
						lock.wait();
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

class PrintNumber extends Thread {
	private Object lock;

	public PrintNumber(Object lock) {
		this.lock = lock;
	}

	@Override
	public void run() {
		synchronized (lock) {
			for (int i = 1; i <= 26; i++) {
				System.out.print(i * 2 - 1);
				System.out.print(i * 2);
				try {
					//唤醒
					lock.notifyAll();
					//等待
					if (i != 26) {
						lock.wait();
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
